/*
 * @Author: sdq 483657864@qq.com
 * @Date: 2025-04-18 10:06:00
 * @LastEditors: sdq 483657864@qq.com
 * @LastEditTime: 2025-04-18 17:17:19
 * @FilePath: \ranyu_anchor_new\src\agroa\listenter\userPublished.ts
 * @Description: 用户推流监听
 */
// import { agoraClient } from "../initAgroaSdk";
import { type IAgoraRTCRemoteUser } from "agora-rtc-sdk-ng";
export const agoraPublishedListener = async () => {
  // 动态导入，减少不必要的加载
  const { agoraClient } = await import("../initAgoraSdk");
  const { handleError } = await import("../auxiliary");
  const { useRemoteStore } = await import("@/store");
  const remoteStore = useRemoteStore();
  /**
   * @description 推流监听
   */
  const mountPublishedLister = () => {
    agoraClient.value?.on("user-published", async (user, mediaType) => {
      if (mediaType !== "audio") return;
      await updateRemoteUserList(user); //无论是否是黑名单都添加到远端用户列表
      await autoSubscribed(user); //自动订阅
    });
  };
  /**
   * 添加上麦用户到列表
   * @param {IAgoraRTCRemoteUser}user - 推流对象
   */
  const updateRemoteUserList = async (user: IAgoraRTCRemoteUser) => {
    remoteStore.updateRemoteUsers("add", user.uid);
  };
  /**
   * 自动订阅逻辑，需要判断是否处于黑名单
   * @param {IAgoraRTCRemoteUser}user - 推流对象
   */
  const autoSubscribed = async (user: IAgoraRTCRemoteUser) => {
    if (remoteStore.manualUnsubscribed.has(user.uid)) return;
    try {
      await agoraClient.value?.subscribe(user, "audio");
      user.audioTrack?.play();
      remoteStore.updateUserSubscription(user.uid, true);
    } catch (error) {
      handleError("自动订阅失败", error);
    }
  };
  return {
    mountPublishedLister,
  };
};
